//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package dev_container_dao

import (
	"context"

	"atomgit.com/openlinksaas/api-server/dao/db_ns"
	"atomgit.com/openlinksaas/proto-gen-go.git/dev_container_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type PkgDbItem struct {
	Name      string `bson:"_id"`
	PluginUrl string `bson:"pluginUrl"`
}

func (item *PkgDbItem) ToPackageInfo() *dev_container_api.PackageInfo {
	return &dev_container_api.PackageInfo{
		Name:      item.Name,
		PluginUrl: item.PluginUrl,
	}
}

type _PkgDao struct {
	mc *mongo.Collection
}

func newPkgDao(db *mongo.Database) (*_PkgDao, error) {
	mc := db.Collection(db_ns.DB_NS_DEV_CONTAINER + "pkg")
	return &_PkgDao{mc: mc}, nil
}

func (db *_PkgDao) Insert(ctx context.Context, dbItem *PkgDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_PkgDao) Exist(ctx context.Context, pkgName string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": pkgName})
	return count > 0, err
}

func (db *_PkgDao) Remove(ctx context.Context, pkgName string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": pkgName})
	return err
}

func (db *_PkgDao) RemoveAll(ctx context.Context) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{})
	return err
}

func (db *_PkgDao) List(ctx context.Context) ([]*PkgDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{}, options.Find().SetSort(bson.M{"_id": 1}))
	if err != nil {
		return nil, err
	}
	retList := []*PkgDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}
